
import { getByDictValue, getByDictType } from "@/api/system/dict";

const state = {
  // 页面刷新后vuex中的数据就没了，堆栈清空了，所以要保存在外部，
  // sessionStorage浏览器关闭到期，localStorage无期限
  dict: JSON.parse(sessionStorage.getItem("dict")) || new Array(),
  // dict: new Array()
}

const mutations = {
  SET_DICT: (state, data) => {
    if (data.dictValue !== null && data.dictValue !== "") {
      state.dict.push({
        "dictValue": data.dictValue,
        "dictName": data.dictName,
        "dictType": data.dictType,
        "dictType": data.remark,
      })
      sessionStorage.setItem("dict", JSON.stringify(state.dict));
    }
  },
  REMOVE_DICT: (state, key) => {
    try {
      for (let i = 0; i < state.dict.length; i++) {
        if (state.dict[i].key == key) {
          state.dict.splice(i, 1)
          return true
        }
      }
    } catch (e) {
    }
  },
  CLEAN_DICT: (state) => {
    state.dict = new Array()
  }
}

const actions = {
  // 获取单个字典项
  getDictByValue({ commit, state }, key) {
    return new Promise((resolve) => {
      // 遍历所有字典项，若找到了，直接返回，否则查询字典项
      for (let i = 0; i < state.dict.length; i++) {
        if (state.dict[i].dictValue == key) {
          resolve(state.dict[i]);
          return true;
        }
      }
      getByDictValue(key).then(res => {
        let returnData = res.data.data;
        if (returnData) {
          commit('SET_DICT', returnData)
          resolve(returnData)
        }
      })

    })
  },
  // 获取一些字典项
  getDictByType({ commit, state }, key) {
    return new Promise((resolve) => {
      let dictList = [];
      // 遍历所有字典项，若找到了，存入数组中
      for (let i = 0; i < state.dict.length; i++) {
        if (state.dict[i].dictType == key) {
          dictList.push(state.dict[i]);
        }
      }
      // 如果不为空
      if (dictList.length > 0) {
        resolve(dictList);
        return true;
      }
      getByDictType(key).then(res => {
        let returnData = res.data.data;
        if (returnData) {
          for (let i = 0; i < returnData.length; i++) {
            commit('SET_DICT', returnData[i]);
          }
          resolve(returnData);
        }
        return false;
      })

    })
  },
  // 设置字典
  setDict({ commit }, data) {
    commit('SET_DICT', data)
  },
  // 删除字典
  removeDict({ commit }, key) {
    commit('REMOVE_DICT', key)
  },
  // 清空字典
  cleanDict({ commit }) {
    commit('CLEAN_DICT')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

